package com.nineshadow.games.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <p>
 * 定制线程池
 * 1.对线程重命名
 * 2.异常处理
 * </p>
 *
 * @author ting liu
 * @since 2019/5/17 15:48
 */
@Slf4j
public class WorkerThreadFactory implements ThreadFactory {
    private final AtomicLong counter = new AtomicLong(0);
    private String prefix;

    public WorkerThreadFactory(String prefix) {
        this.prefix = prefix;
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, prefix + "-" + counter.getAndIncrement());
        t.setUncaughtExceptionHandler((t1, e) -> log.error("线程" + t1.getName() + "执行出错：", e));
        return t;
    }
}
